package com.qdy.api;

import com.jiai.core.tools.RestResultGenerator;
import com.jiai.core.util.IdGenerate;
import com.jiai.exception.ServiceException;
import com.qdy.common.util.NetworkUtil;
import com.qdy.entity.Order;
import com.qdy.entity.user.User;
import com.qdy.pay.common.WeixinConfigure;
import com.qdy.pay.mode.WeiXinPayData;
import com.qdy.pay.service.WeiXinAppPayService;
import com.qdy.repository.OrderRepository;
import com.qdy.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 微信支付接口
 */
@RestController
public class WeiXinAppPayAPIController {
    private static Logger log= LoggerFactory.getLogger(WeiXinAppPayAPIController.class);
    @Autowired
    private OrderRepository orderRepository;

    @RequestMapping(value = "/weixin/pay",method = RequestMethod.POST)
    private Object pay(WeiXinPayData weiXinPayData, HttpServletRequest request)throws ServiceException{
         try{
             log.info("==========================================");
             User user= HttpUtil.getUser();
             log.info(user.toString());
             String  orderId= IdGenerate.getOrderIdByUUId();
             String userIP= NetworkUtil.getIpAddress(request);
             weiXinPayData.setNotify_url(WeixinConfigure.getNotify_url());
             weiXinPayData.setOpenid(user.getOpenId());
             weiXinPayData.setOut_trade_no(orderId);
             weiXinPayData.setSpbill_create_ip(userIP);
             Map<String,Object> data=new WeiXinAppPayService().request(weiXinPayData);
             Order order=new Order();
             Date now=new Date();
             order.setBody(weiXinPayData.getBody());
             Calendar calendar=Calendar.getInstance();
             calendar.setTime(now);
             calendar.add(Calendar.MINUTE,30);
             order.setTimeStart(now.getTime()+"");
             order.setTimeExpire(calendar.getTime().getTime()+"");
             order.setPayType(1);
             order.setOrderDate(new Date());
             order.setOrderNo(orderId);
             order.setStatu(0);
             order.setTotalFee(BigDecimal.valueOf(weiXinPayData.getTotal_fee()));
             order.setTransactionId(data.get("payId").toString());
             order.setUserId(user.getId());
             orderRepository.save(order);
             return RestResultGenerator.genSuccessResult(data.get("sign"));
         }catch (Exception e){

             throw new ServiceException("生成预付订单失败!"+e.getMessage());
         }
    }

}
